import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from pymysql import *
from data_type import *
import pickle

class Table(QWidget):
    def __init__(self):
        super().__init__()
        
        self.info = []   #记录从数据库获取的信息，每个元素是一个列表
        
        # self.pkt = []    #记录从文件获取的信息，每个元素是一个packet类
        
        self.setGeometry(300, 300, 1500, 800)  #界面显示位置和大小
        self.setWindowTitle('QTableWidget的基本用法')

        layout = QHBoxLayout()
        self.table = QTableWidget()       #初始化
        self.table.setRowCount(0)         #设置行数
        self.table.setColumnCount(6)      #设置列数
        #可根据窗口大小来改变网格的大小
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        #整行选中
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        #将行和列的高度、宽度设置为与所显示内容的宽度、高度相匹配
        self.table.resizeRowsToContents()
        self.table.resizeColumnsToContents()

        # #在单元格中放置控件
        # btn = QPushButton('修改')
        # btn.setDown(True)
        # #修改按钮大小
        # btn.setStyleSheet("QPushButton{margin:3px};")
        # #将按钮添加到单元格
        # table.setCellWidget(1,0,btn)

        layout.addWidget(self.table)
        header = ['Time', 'Type', 'Src', 'Dst', 'Sport', 'Dport']
        self.table.setHorizontalHeaderLabels(header)
        self.setLayout(layout)
        
        self.ReadInfoFromDatabase()
        # self.ReadPktFromPkl()
        
        # print(len(self.pkt))
        
        for i in range(len(self.info)):
            self.appendData(self.info[i])
            
        # self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        # #将右键菜单绑定槽函数
        # self.table.customContextMenuRequested.connect(self.Menu)
            
    def ReadInfoFromDatabase(self):
        try:
            conn = connect(host='127.0.0.1', port=3306, user='root', password='020903chen..', db='protocol_infomation')
        except:
            print("绘制表格读数据时连接失败！")
            
        cur = conn.cursor()
        
        tableName = "keyInfo"
            
        sql = ''' SELECT * FROM `%s`;''' %tableName
        cur.execute(sql)
        data3 = cur.fetchall()
        for d in data3:
            d = list(d)
            self.info.append(d)
            #print(d)

        conn.commit()
        cur.close()  # 关闭游标
        conn.close()  # 关闭数据库连接
     
    # def ReadPktFromPkl(self):
    #     Ethernet = EthernetPkt()
    #     Ipv4 = Ipv4Pkt()
    #     Ipv6 = Ipv6Pkt()
    #     Tcp = TcpPkt()
    #     Udp = UdpPkt()
    #     Arp = ArpPkt()
    #     Dns = DnsPkt()
    #     Icmpv4 = Icmpv4Pkt()
    #     Icmpv6 = Icmpv6Pkt()
    #     HttpReq = HttpReqPkt()
    #     HttpRes = HttpResPkt()
    
    #     eachPkt = Packet(Ethernet, Ipv4, Ipv6, Tcp, Udp, Arp, Dns, Icmpv4, Icmpv6, HttpReq, HttpRes)
    #     with open("sniffRes//cur//demo.pkl",'rb') as f:
    #         while 1:
    #             try:
    #                 eachPkt = pickle.load(f)
    #                 self.pkt.append(eachPkt)
    #                 # print(eachPkt)
    #                 # eachPkt.PrintFlag()
    #             except EOFError:
    #                 break
        
    def appendData(self, data):
        row = self.table.rowCount()
        self.table.insertRow(row)

        time = QTableWidgetItem(str(data[1]))
        time.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)

        type = QTableWidgetItem(str(data[2]))
        type.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)

        src = QTableWidgetItem(data[3])
        src.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
        
        dst = QTableWidgetItem(data[4])
        dst.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)

        sport = QTableWidgetItem(data[5])
        sport.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)

        dport = QTableWidgetItem(data[5])
        dport.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)

        self.table.setItem(row, 0, time)
        self.table.setItem(row, 1, type)
        self.table.setItem(row, 2, src)
        self.table.setItem(row, 3, dst)
        self.table.setItem(row, 4, sport)
        self.table.setItem(row, 5, dport)

        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setSelectionMode(QAbstractItemView.SingleSelection)
        
    # def Menu(self, pos):
    #     # row_num = -1
    #     # for i in table.selectionModel().selection().indexes():
    #     #     row_num = i.row()
    #     # # 表格中只有两行数据，所以只在前两行支持右键弹出菜单
    #     # if row_num < 2:
    #     for p in self.pkt:
    #         menu = QMenu()
    #         menu = QMenu()
    #         for pkey in p.GetFlag():
    #             if p.GetFlag()[pkey] == 1:
    #                 menu.addAction('查看' + pkey + '层详细信息')
    #         menu.exec_(self.table.mapToGlobal(pos))
            
    # def dynamicAppend(self):
    #     for i in range(len(self.info)):
    #         self.appendData(self.info[i])

if __name__ == "__main__":
    app = QApplication(sys.argv)
    form = Table()
    form.show()
    sys.exit(app.exec_())